import { hasPermission, hasRole, hasPermissionOrRole } from '@/utils/permission'

/**
 * 权限控制指令
 * 使用方式：
 * v-permission="'user_manage'" - 检查是否有指定权限
 * v-permission.role="'ADMIN'" - 检查是否有指定角色
 * v-permission.or="['user_manage', 'ADMIN']" - 检查是否有权限或角色
 */
export const permission = {
  mounted(el, binding) {
    const { value, modifiers } = binding
    let hasAccess = false

    if (modifiers.role) {
      // 检查角色
      hasAccess = hasRole(value)
    } else if (modifiers.or) {
      // 检查权限或角色
      if (Array.isArray(value)) {
        hasAccess = value.some(item => hasPermission(item) || hasRole(item))
      } else {
        hasAccess = hasPermissionOrRole(value, value)
      }
    } else {
      // 检查权限
      hasAccess = hasPermission(value)
    }

    if (!hasAccess) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const { value, modifiers } = binding
    let hasAccess = false

    if (modifiers.role) {
      hasAccess = hasRole(value)
    } else if (modifiers.or) {
      if (Array.isArray(value)) {
        hasAccess = value.some(item => hasPermission(item) || hasRole(item))
      } else {
        hasAccess = hasPermissionOrRole(value, value)
      }
    } else {
      hasAccess = hasPermission(value)
    }

    if (hasAccess) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
}

/**
 * 角色控制指令
 * 使用方式：
 * v-role="'ADMIN'" - 检查是否有指定角色
 * v-role="['ADMIN', 'TEACHER']" - 检查是否有指定角色之一
 */
export const role = {
  mounted(el, binding) {
    const hasAccess = hasRole(binding.value)
    if (!hasAccess) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const hasAccess = hasRole(binding.value)
    if (hasAccess) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
} 